﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace GraduationProject.Webs.Areas.Admin
{
    public class NewtonsoftJson : JsonResult
    {
        public NewtonsoftJson()
        {

        }
        /// <param name="data">序列化数据源</param>
        /// <param name="Format">序列化数据源时间格式</param>
        /// <param name="behavior"></param>
        /// <param name="contentType"></param>
        /// <param name="contentEncoding"></param>
        public NewtonsoftJson(object data, string Format = "yyyy-MM-dd HH:mm:ss", JsonRequestBehavior behavior = JsonRequestBehavior.AllowGet, string contentType = null, System.Text.Encoding contentEncoding = null)
        {
            this.Data = data;
            this.Format = Format;
            this.JsonRequestBehavior = behavior;
            this.ContentEncoding = contentEncoding;
            this.ContentType = contentType;
            this.MaxJsonLength = Int32.MaxValue;
        }
        /// <summary>
        /// 设置时间显示格式
        /// </summary>
        public string Format { get; set; }

        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context");
            if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
                throw new InvalidOperationException("JSON GET is not allowed");

            HttpResponseBase response = context.HttpContext.Response;
            response.ContentType = string.IsNullOrEmpty(this.ContentType) ? "application/json" : this.ContentType;

            if (this.ContentEncoding != null)
                response.ContentEncoding = this.ContentEncoding;
            if (this.Data == null)
                return;
            response.Write(JsonHelper.SerializeObject(this.Data, Format));


        }

    }
}